﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static System.Net.Mime.MediaTypeNames;

namespace WpfAppVPN_active
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        static bool isRun = false;

        /// <summary>
        /// 任务剩余存活时长，毫秒
        /// </summary>
        static int live_millseconds = 0;

        public MainWindow()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 运行
        /// </summary>
        public void RunTask()
        {
            isRun = true;
            Task task = new Task(() =>
            {
                while (isRun)
                {
                    //ShowMsg($"任务{Thread.CurrentThread.ManagedThreadId}将在{live_millseconds}毫秒后执行...");
                    if (live_millseconds > 0)
                    {
                        goto TO_SLEEP;
                    }
                DO_TASK:
                    //执行的命令
                    string urlExe = string.Empty;

                    Dispatcher.Invoke(() =>
                    {
                        urlExe = txtUrl.Text;
                    });
                    try
                    {
                        string exe = urlExe.Split(' ')[0];
                        string args = urlExe.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Length > 1 ?
                        urlExe.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[1] : "";
                        if (string.IsNullOrWhiteSpace(args))
                        {
                            System.Diagnostics.Process.Start(exe);
                        }
                        else
                        {
                            System.Diagnostics.Process.Start(exe, args);
                        }
                        Dispatcher.InvokeAsync(() =>
                        {
                            string msg = $"{Thread.CurrentThread.ManagedThreadId}执行成功";
                            ShowMsg(msg);
                        });
                    }
                    catch (Exception ex)
                    {
                        var ex1 = ex.InnerException ?? ex;
                        string msg = "出错：" + ex1.Message;
                        ShowMsg(msg);
                    }

                TO_SLEEP:
                    if (live_millseconds > 2000)
                    {
                        Thread.Sleep(2000);
                        live_millseconds -= 2000;
                    }
                    else
                    {
                        try
                        {
                            Thread.Sleep(live_millseconds);

                            Dispatcher.Invoke(() =>
                            {
                                //重置存活时间
                                if (int.TryParse(txtTimeSpan.Text.Trim(), out live_millseconds))
                                { }
                            });

                            if (isRun)
                            {
                                //开始执行命令
                                goto DO_TASK;
                            }
                        }
                        catch (Exception ex)
                        {
                            var ex1 = ex.InnerException ?? ex;
                            ShowMsg("DO_TASK异常," + ex1.Message);
                        }
                    }
                }
                ShowMsg($"任务{Thread.CurrentThread.ManagedThreadId}结束");
                Dispatcher.InvokeAsync(() => {
                    btnStart.IsEnabled = true;
                });               
            }, TaskCreationOptions.LongRunning);
            task.Start();
        }

        private static object obj = new object();

        //确定，开始
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //isRun = false;
            lock (obj)
            {
                if (!isRun)
                {
                    //间隔时间，毫秒
                    if (int.TryParse(txtTimeSpan.Text.Trim(), out live_millseconds))
                    {
                        btnStart.IsEnabled = false;
                        ShowMsg("开始 ");
                        RunTask();
                    }
                }          
            }
        }

        //停止
        private void Stop_Click(object sender, RoutedEventArgs e)
        {
            if (isRun)
            {
                btnStart.IsEnabled = false;
                isRun = false;
                live_millseconds = 0;
                ShowMsg("停止中...");                                
            }
        }

        //只准输入数字
        private void txtTimeSpan_KeyUp(object sender, KeyEventArgs e)
        {
            TextBox textBox = txtTimeSpan; // sender as TextBox;
            if (!string.IsNullOrWhiteSpace(textBox.Text))
            {
                if (textBox.Text == "0.0" || textBox.Text.StartsWith("00"))
                {
                    textBox.Text = textBox.Text.Replace("00", "");
                }

                //只准输入正整数
                //Regex regex2 = new Regex(@"(\+|\-)?\d+\.?\d*", RegexOptions.IgnoreCase);
                Regex regex2 = new Regex(@"\d+", RegexOptions.IgnoreCase);
                textBox.Text = regex2.Match(textBox.Text).Value;
            }
        }

        //输入间隔改变，停止任务
        private void txtTimeSpan_TextChanged(object sender, TextChangedEventArgs e)
        {
            //Stop_Click(sender, e);
            isRun = false;
        }

        /// <summary>
        /// 显示消息
        /// </summary>
        /// <param name="msg"></param>
        private void ShowMsg(string msg)
        {
            if (string.IsNullOrWhiteSpace(msg))
            {
                return;
            }
            string msg2 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "," + msg;
            Dispatcher.Invoke(new Action(() =>
            {
                listBox1.Items.Add(msg2);
                listBox1.ScrollIntoView(msg2);
            }));

        }
    }
}
